package com.meterreadingsys.httpserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;

import org.apache.http.protocol.HttpContext;


import com.meterreadingsys.httpserver.CustomMultiPartEntity.ProgressListener;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;

public class HttpMultipartPost extends AsyncTask<String, Integer, String> {

	public ProgressDialog pd;
	public long totalSize;
	public Context context;
	public File file;
	public HttpPost httpPost=null;
	public Map<String, String> param;//普通参数
	public HttpMultipartPost(Context context,Map<String, String> param,File file) {
		this.param=param;
		this.context = context;
		this.file=file;

	}

	@Override
	protected void onPreExecute() {
		pd = new ProgressDialog(context);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setTitle("上传中.......");
		
		pd.setCancelable(false);
		
		pd.setButton("取消下载",new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				System.out.println("取消下载");
				
			}
		});
		pd.show();

	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		if (values[0] == 100) {
			pd.cancel();
			
		}
       
		pd.setProgress((int) (values[0]));

		pd.setMessage(formatSize(values[0]) + "/" + formatSize(totalSize));

	}

	protected void onPostExecute(String result) {
		pd.dismiss();
	}

	@Override
	protected String doInBackground(String... params) {
		String tempLine="";
		HttpClient httpClient = new DefaultHttpClient();
		HttpContext httpContext = new BasicHttpContext();
		System.out.println(params[0]);
		 httpPost = new HttpPost(params[0]);

		CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(
				new ProgressListener() {

					@Override
					public void transferred(long num) {
						if (num % 2 == 0) {
							 publishProgress((int) ((num / (float) totalSize) * 100));
						}
						if(num==totalSize){
							publishProgress(100);
						}
					
					}
				});
		//jdk-6u24-windows-i586.exe
    
      if(! file.exists()){
    	  System.out.println("没有找到文件");
    	  close();
    	  return null;
      }
       System.out.println(file.getName());
         FileBody filebody=new FileBody(file);
        
         //添加上传文件
		multipartContent.addPart("image", filebody);
		
		//添加普通参数
		if (param != null && !param.isEmpty()) {
			for (Map.Entry<String, String> entry : param.entrySet()) {
				try {
					multipartContent.addPart(entry.getKey(), new StringBody(entry.getValue()));
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		totalSize = multipartContent.getContentLength();
		
		
		// Send it
		httpPost.setHeader("Charset", "utf-8");
		httpPost.setEntity(multipartContent);
		
	
		HttpResponse response;
		try {
			response = httpClient.execute(httpPost, httpContext);

			int stateCode = response.getStatusLine().getStatusCode();
			StringBuffer sb = new StringBuffer();
			if (stateCode == HttpStatus.SC_OK) {

				HttpEntity result = response.getEntity();
				if (result != null) {
					InputStream is = result.getContent();
					BufferedReader br = new BufferedReader(
							new InputStreamReader(is));
					
					while ((tempLine = br.readLine()) != null) {
						sb.append(tempLine);
					}
				}

			}
			httpPost.abort();
			
	

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return "error";
		} catch (IOException e) {
			return "error";
		}

		return tempLine;
	}

	public static String formatSize(float size)

	{

		long kb = 1024;

		long mb = (kb * 1024);

		long gb = (mb * 1024);

		if (size < kb) {

			return String.format("%d B", (int) size);

		}

		else if (size < mb) {

			return String.format("%.2f KB", size / kb); // 保留两位小数

		}

		else if (size < gb) {

			return String.format("%.2f MB", size / mb);

		}

		else {

			return String.format("%.2f GB", size / gb);

		}

	}
	
     public void close(){
	  try {
		  if(httpPost!=null)
		httpPost.clone();
		  pd.cancel();
	} catch (CloneNotSupportedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
  }
}
